const fs = require('fs')
const verify = require('../../auth/verify.js')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')
const config = require('../../config.js')

/**
 * @description 上传图片
 */
module.exports = function () {
	const that = this
	const authorization = this.request.headers.authorization
	/**
	 * @description 请求方式验证
	 */
	verifyRequestMethod(this.request, 'POST').then(function () {
		/**
		 * @description 授权验证
		 */
		if (that.isDef(authorization)) {
			return verify(authorization)
		} else {
			return Promise.reject(new Error('缺少Authorization！'))
		}
	}).then(function (data) {
		/**
		 * @description 获取文件流
		 */
		return that.getFileStream(that.request)
	}).then(function (file) {
		/**
		 * @description 文件流转buffer
		 */
		return that.parseBinaryForBuffer(file.image)
	}).then(function (result) {
		/**
		 * @description 创建文件
		 */
		const imageType = that.image.matchImageMType(result.type)
		if (!!imageType && that.image.isImage(imageType)) {
			if (result.size / 1024 <= config.MAX_FILE_SIZE) {
				fs.writeFile(`${config.FILE_IMAGE_PATH}${result.name}.${imageType}`, result.buffer, function (err) {
					if (err) {
						that.response.outPrintError('操作失败！')
					} else {
						that.response.outPrintData({ name: `${result.name}.${imageType}` }, '上传成功！')
					}
				})
			} else {
				that.response.outPrintError('文件太大，最大支持2MB！')
			}
		} else {
			that.response.outPrintError('格式错误，不是一张图片！')
		}
	}).catch(function (e) {
		that.response.outPrintError((e && e.message) || '未知错误！')
	})
}
